package com.gulimall.cart.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.gulimall.cart.to.UserInfoTo;
import com.gulimall.common.constrant.AuthServerConstant;
import com.gulimall.common.constrant.CartConstant;
import com.gulimall.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


/**
 * @author kkk
 * @date 2022/8/2
 * 在执行方法之前，判断用户的登录状态，并封装传递给controller目标请求
 */
@Component
public class CartUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>();

    /**
     * 在方法执行前
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_INFO);
        MemberRespVo memberRespVo = attribute == null ? null :
                JSONObject.parseObject(JSONObject.toJSONString(attribute), MemberRespVo.class);
        UserInfoTo userInfoTo = new UserInfoTo();
        if (memberRespVo != null) {
            userInfoTo.setUserId(memberRespVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.CART_COOKIE_TEMP_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }
        //cookie中没有值，随机生成一个
        if (!StringUtils.hasText(userInfoTo.getUserKey())) {
            userInfoTo.setUserKey(UUID.randomUUID().toString());
            userInfoTo.setLogin(true);
        }

        //在方法执行前
        toThreadLocal.set(userInfoTo);

        return true;
    }

    /**
     * 方法执行之后
     *
     * @param request  current HTTP request
     * @param response current HTTP response* @param modelAndView the {@code ModelAndView} that the handler returned
     *                 (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = toThreadLocal.get();
        if (userInfoTo.isLogin()) {
            Cookie cookie = new Cookie(CartConstant.CART_COOKIE_TEMP_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
